<?php
namespace app\api\service\uniapp\index;

use app\api\model\Region;
use app\api\model\ShopActivity;
use app\api\model\ShopYiwu;
use app\api\service\uniapp\goods\Goods;
use app\api\service\uniapp\shop\Shop;
use app\common\controller\Api;
use think\Db;

class Index10 extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function index(){
        //接收参数
        $page = $this->request->param('page');       //页码
        $size = $this->request->param('size');       //每页显示
        $page = ($page-1)*$size;
        $current = $this->request->param('current'); //数据类型：0=特别推荐，1=今日新品，2=所有商品
        $city = $this->request->param('city',"桂林市");       //城市
        $city = empty($city)?"桂林市":$city;
        $lat = $this->request->param('lat',"25.2409");       //城市
        $lng = $this->request->param('lng',"110.3283");       //城市
        //获取检查定位
        //获取广告图片
        //获取数据列表
        $city_id = Region::where('name',$city)->value('id');
        // 查询店铺并按距离排序
        $shops = Db::table('tp_user_store')
            ->field([
                'id',
                'store_name',
                'lat',
                'lng',
                // 计算距离（单位：千米），AS 定义为 distance_km 用于排序
                '6371 * 2 * ASIN(
                    SQRT(
                        POW(SIN((' . $lat . ' - lat) * PI() / 180 / 2), 2) +
                        COS(' . $lat . ' * PI() / 180) * COS(lat * PI() / 180) *
                        POW(SIN((' . $lng . ' - lng) * PI() / 180 / 2), 2)
                    )
                ) AS distance_km'
            ])
            // 可选：通过经纬度范围过滤，减少计算量
            ->where(['city_id'=>$city_id,'is_check'=>1])
            // 按距离升序排序（最近的在前）
            ->order('distance_km', 'asc')
            ->select();
        $shop_ids = array();
        foreach ($shops as $k=>$v){
            array_push($shop_ids,$v['id']);
        }
        if($current==0){
            $shopwhere = "is_tj=1";
        }else if($current==1){
            $shopwhere = "is_xp=1";
        }else{
            $shopwhere = "1=1";
        }
        //halt($shopwhere);
        $goods = ShopYiwu::where(['shop_id'=>array('in',$shop_ids),'is_check'=>1])->where($shopwhere)->limit($page,$size)->select();
        $leftheight = 0;
        $rightheight = 0;
        $height100 = 0;
        $leftdata = array();
        $rightdata = array();
        foreach ($goods as $k=>$v){
            //判断是否有缩图
            if(empty($v['thumb_pic']) || strstr($v['thumb_pic'],'/thumb/')===false){
                $thumbimg = get_thumb_image(unserialize($v['main_pics'])[0],0,300);
                //halt($thumbimg);
                $v['thumb_pic'] = $thumbimg;
                ShopYiwu::where('id',$v['id'])->update(['thumb_pic'=>'/public'.$thumbimg]);
            }

            //$filepath = ROOT_PATH . $v['thumb_pic'];
            $filepath = "." . $v['thumb_pic'];
            if(is_file($filepath)){
                $imginfo = getimagesize($filepath);
                $width = $imginfo[0];  // 宽度（像素）
                $height = $imginfo[1]; // 高度（像素）
                $newheight = intval(155.52*($height/$width));//intval(200/$width*$height);
                //dump("当前：".$newheight.",左：".$leftheight.",右：".$rightheight);
                if($leftheight>$rightheight){
                    $rightheight+=$newheight;
                    array_push($rightdata,$v);
                }else{
                    $leftheight+=$newheight;
                    array_push($leftdata,$v);
                }
            }else{
                $height100++;
                $width = 100;  // 宽度（像素）
                $height = 100; // 高度（像素）
                $newheight = intval(100/$width*$height);
                if($leftheight>$rightheight){
                    $rightheight+=$newheight;
                    array_push($rightdata,$v);
                }else{
                    $leftheight+=$newheight;
                    array_push($leftdata,$v);
                }
            }
            $goods[$k]['thumb_pic'] = config('img_url').$v['thumb_pic'];
        }
        $data['leftheight'] = $leftheight;
        $data['rightheight'] = $rightheight;
        $data['leftdata'] = $leftdata;
        $data['rightdata'] = $rightdata;
        $data['height100'] = $height100;
        $this->success('加载成功',$data);
    }
    public function load_list(){
        //接收参数
        $page = $this->request->param('page');       //页码
        $size = $this->request->param('size');       //每页显示
        $page = ($page-1)*$size;
        $current = $this->request->param('current'); //数据类型：0=特别推荐，1=今日新品，2=所有商品
        $city = $this->request->param('city',"桂林市");       //城市
        $city = empty($city)?"桂林市":$city;
        $lat = $this->request->param('lat',"25.2409");       //城市
        $lng = $this->request->param('lng',"110.3283");       //城市
        //获取检查定位
        //获取广告图片
        $data['ads_img'] = '';//config('img_url')."upload/ad/04fd468bbb0c2f970b4757994067f5b5.jpg";
        //是否显示分类列表
        $data['show_catlist'] = false;
        //是否显示导航
        $data['show_nav'] = false;
        //获取数据列表
        $city_id = Region::where('name',$city)->value('id');
        // 查询店铺并按距离排序
        $shops = Db::table('tp_user_store')
            ->field([
                'id',
                'store_name',
                'lat',
                'lng',
                // 计算距离（单位：千米），AS 定义为 distance_km 用于排序
                '6371 * 2 * ASIN(
                    SQRT(
                        POW(SIN((' . $lat . ' - lat) * PI() / 180 / 2), 2) +
                        COS(' . $lat . ' * PI() / 180) * COS(lat * PI() / 180) *
                        POW(SIN((' . $lng . ' - lng) * PI() / 180 / 2), 2)
                    )
                ) AS distance_km'
            ])
            // 可选：通过经纬度范围过滤，减少计算量
            ->where(['city_id'=>$city_id,'is_check'=>1])
            // 按距离升序排序（最近的在前）
            ->order('distance_km', 'asc')
            ->select();
        $shop_ids = array();
        foreach ($shops as $k=>$v){
            array_push($shop_ids,$v['id']);
        }
        if($current==0){
            $shopwhere = "is_tj=1";
        }else if($current==1){
            $shopwhere = "is_xp=1";
        }else{
            $shopwhere = "1=1";
        }
        //halt($shopwhere);
        $goods = ShopYiwu::where(['shop_id'=>array('in',$shop_ids),'is_check'=>1,'is_on_sale'=>1])->where($shopwhere)->limit($page,$size)->select();
        foreach ($goods as $k=>$v){
            //判断是否有缩图
            if(empty($v['thumb_pic']) || strstr($v['thumb_pic'],'/thumb/')===false){
                $thumbimg = get_thumb_image(unserialize($v['main_pics'])[0],0,300);
                //halt($thumbimg);
                $v['thumb_pic'] = $thumbimg;
                ShopYiwu::where('id',$v['id'])->update(['thumb_pic'=>'/public'.$thumbimg]);
            }

            $goods[$k]['thumb_pic'] = config('img_url').$v['thumb_pic'];
        }
        $data['goods'] = $goods;
        $this->success('加载成功',$data);
    }

    public function load_ads(){
        //接收参数
        $page = $this->request->param('page');       //页码
        $size = $this->request->param('size');       //每页显示
        $page = ($page-1)*$size;
        $current = $this->request->param('current'); //数据类型：0=特别推荐，1=今日新品，2=所有商品
        $city = $this->request->param('city',"桂林市");       //城市
        $city = empty($city)?"桂林市":$city;
        $lat = $this->request->param('lat',"25.2409");       //城市
        $lng = $this->request->param('lng',"110.3283");       //城市
        //获取检查定位
        //获取广告图片
        $data['ads_img'] = config('img_url')."upload/ad/dfa329b17bc7cd6965aee30d57c8c807.jpg";
        //是否显示分类列表
        $data['show_catlist'] = false;
        //获取数据列表
        $city_id = Region::where('name',$city)->value('id');
        // 查询店铺并按距离排序
        $shops = Db::table('tp_user_store')
            ->field([
                'id',
                'store_name',
                'lat',
                'lng',
                // 计算距离（单位：千米），AS 定义为 distance_km 用于排序
                '6371 * 2 * ASIN(
                    SQRT(
                        POW(SIN((' . $lat . ' - lat) * PI() / 180 / 2), 2) +
                        COS(' . $lat . ' * PI() / 180) * COS(lat * PI() / 180) *
                        POW(SIN((' . $lng . ' - lng) * PI() / 180 / 2), 2)
                    )
                ) AS distance_km'
            ])
            // 可选：通过经纬度范围过滤，减少计算量
            ->where(['city_id'=>$city_id,'is_check'=>1])
            // 按距离升序排序（最近的在前）
            ->order('distance_km', 'asc')
            ->select();
        $shop_ids = array();
        foreach ($shops as $k=>$v){
            array_push($shop_ids,$v['id']);
        }
        //halt($shopwhere);
        $goods = ShopActivity::where(['shop_id'=>array('in',$shop_ids),'is_check'=>1,'is_on_sale'=>1])->limit($page,$size)->select();
        foreach ($goods as $k=>$v){
            //判断是否有缩图
            if(empty($v['thumb_pic']) || strstr($v['thumb_pic'],'/thumb/')===false){
                $thumbimg = get_thumb_image(unserialize($v['main_pics'])[0],0,300);
                //halt($thumbimg);
                $v['thumb_pic'] = $thumbimg;
                ShopActivity::where('id',$v['id'])->update(['thumb_pic'=>'/public'.$thumbimg]);
            }

            $goods[$k]['thumb_pic'] = config('img_url').$v['thumb_pic'];
        }
        $data['goods'] = $goods;
        $this->success('加载成功',$data);
    }

    public function search(){
        //接收参数
        $search_type = $this->request->param('search_type');
        $search_key = $this->request->param('search_key');
        if(empty($search_key)){
            $this->success('加载成功',[]);
        }
        if ($search_type==0){
            $goodsService = new Goods();
            $list = $goodsService->getGoodsByKey($search_key);
        }
        if ($search_type==1){
            $shopService = new Shop();
            $list = $shopService->getShopByKey($search_key);
        }
        $this->success('加载成功',$list);
    }
}